from models import Model
from models.todo import Todo


class User(Model):
    def __init__(self, form):
        self.id = form.get('id', None)
        if self.id is not None:
            self.id = int(self.id)
        self.username = form.get('username', '')
        self.password = form.get('password', '')
        # self.role = int(form.get('role', 10))

    # def is_admin(self):
    #     return self.role == 1

    def validate_login(self):
        us = User.all()
        for u in us:
            if u.username == self.username and u.password == self.password:
                return True
        return False

    def validate_register(self):
        return len(self.username) > 2 and len(self.password) > 2

    def todos(self):
        # 列表推倒和过滤
        # return [t for t in Todo.all() if t.user_id == self.id]
        ts = []
        for t in Todo.all():
            if t.user_id == self.id:
                ts.append(t)
        return ts
